package com.sprite.framework.entity.condition;


import com.sprite.framework.entity.EntityException;
import com.sprite.framework.entity.DataScriptStatement;
import com.sprite.framework.entity.EntityCondition;
import com.sprite.framework.entity.model.ModelEntityView;
import com.sprite.utils.UtilMisc;

/**
 * <p>比较操作</p>
 * @author Jack
 *
 * @param <L> 
 * 			左侧操作值
 * @param <R> 
 * 			右侧操作值
 */
public abstract class EntityComparisonOperator<L,R> extends EntityOperator<L, R, Boolean> {

	
	protected EntityComparisonOperator(int id, String code) {
		super(id, code);
	}
	
	@Override
	public void makeScript(DataScriptStatement script,L l, R r, ModelEntityView modelViewEntity) throws EntityException{
		script.append(" ");
		if(l instanceof EntityCondition){
			script.append("(");
			EntityCondition condition = UtilMisc.cast(l);
			condition.makeScript(script, modelViewEntity);
		}else if(l instanceof NoParameterized){
			NoParameterized p = (NoParameterized)r;
			script.append(p.safeString());
		}else if(l instanceof String){
			String fieldName = (String)l;
			if(modelViewEntity != null){
				script.append(modelViewEntity.resolveFieldPath(fieldName));
			}else{
				script.append(fieldName);
			}
			
		}else{
			throw new RuntimeException("unsupport type ");
		}
		
		script.append(" ");
		script.append(getCode());
		script.append(" ");
		if(r instanceof EntityCondition){
			EntityCondition condition = UtilMisc.cast(r);
			condition.makeScript(script, modelViewEntity);
			script.append(")");
		}else if(r instanceof NoParameterized){
			NoParameterized p = (NoParameterized)r;
			if(!p.isOpenQuote() && NoParameterized.NULL != r){
				if(modelViewEntity != null){
					script.append(modelViewEntity.resolveFieldPath(p.safeString()));
				}else{
					script.append(p.safeString());
				}
			}else{
				script.append(p.safeString());
			}
			
		}else {
			script.append(" ? ");
			script.addParam(r);
		}
	}

}
